package com.zhubayi.shirodb.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.zhubayi.shirodb.entity.MyRealm;
import com.zhubayi.shirodb.service.UserService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author zhubayi
 */
@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("getSecurityManager") SecurityManager securityManager){
        //创建shiro的filter
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //注入安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String,String> map =  new LinkedHashMap<>();
        map.put("/user/login","anon");//放行登录接口
        map.put("/user/register","anon");//放行登录接口
        map.put("/toLogin","anon");//放行登录接口
        map.put("/toRegister","anon");//放行登录接口
        map.put("/getImage","anon");//放行验证码
        map.put("/**","authc");
        //配置认证和授权规则
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }
    @Bean
    public DefaultWebSecurityManager getSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }
    @Bean
    public Realm getRealm(UserService userService){
        MyRealm myRealm = new MyRealm(userService);
        //设置hash的凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置md5加密
        credentialsMatcher.setHashAlgorithmName("md5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        myRealm.setCredentialsMatcher(credentialsMatcher);

        //开启缓存管理
        myRealm.setCacheManager(new RedisCacheManager());
        myRealm.setCachingEnabled(true);//开启全局缓存
        myRealm.setAuthenticationCachingEnabled(true);//认证认证缓存
        myRealm.setAuthenticationCacheName("authenticationCache");
        myRealm.setAuthorizationCachingEnabled(true);//开启授权缓存
        myRealm.setAuthorizationCacheName("authorizationCache");

        return myRealm;
    }
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
